package cn.glutnn.service.impl;

import cn.glutnn.entity.Result;
import cn.glutnn.entity.dto.LoginDTO;
import cn.glutnn.entity.dto.RegisterDTO;
import cn.glutnn.mapper.UserMapper;
import cn.glutnn.service.UserService;
import cn.glutnn.utils.JwtUtil;
import cn.glutnn.utils.Md5Util;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import cn.glutnn.entity.User;

import java.util.Date;
import java.util.HashMap;

/**
 * 用户信息(User)表服务实现类
 *
 * @author msh
 * @since 2024-12-09 19:55:27
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login(LoginDTO loginDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, loginDTO.getUsername());
        User user = getOne(wrapper);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!Md5Util.checkPassword(loginDTO.getPassword(), user.getPassword())) {
            return Result.error("密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        String token = JwtUtil.genToken(map);

        // 将token存入redis
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set("miguToken", token);
        return Result.success(token);
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
        if (!registerDTO.getPassword().equals(registerDTO.getRePassword())) {
            return Result.error("两次密码不一致");
        }
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, registerDTO.getUsername()));
        if (user != null) {
            return Result.error("用户已存在");
        }
        User user1 = new User();
        BeanUtils.copyProperties(registerDTO, user1);
        Date date = new Date(System.currentTimeMillis());
        user1.setCreateTime(date);
        user1.setUpdateTime(date);
        user1.setPassword(Md5Util.getMD5String(registerDTO.getPassword()));
        save(user1);
        return Result.success("注册成功");
    }
}

